package auction;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import billing.BillingServerSecure;

import analytics.AnalyticsServer;

public class ConnectionManager extends Thread {
    private boolean running;
    private ServerSocket ss;
    private ExecutorService pool; //Thread pool
    private AccountManager am;
    
    /**
     * Creates new ConnectionManager-Thread and Starts it
     */
    public ConnectionManager(ServerSocket serversocket, AccountManager am, AnalyticsServer analyticsServer, BillingServerSecure billingServer) {
        super();
        this.ss = serversocket;
        this.am = am;
        this.running =true;
        pool= Executors.newCachedThreadPool();
        this.start();
    }
    
    public void diconnect() {
        this.running=false;
        try {
            System.out.println("Closing ServerSocket...");
            ss.close();
        } catch (IOException e) {
           System.out.println("Error: "+e.getMessage());
        }
    }
    
    /**
     * Shutdown the Thread
     */
    public void shutdown(){
        this.running=false;
        try {
            System.out.println("Closing ServerSocket...");
            ss.close();
        } catch (IOException e) {
           System.out.println("Error: "+e.getMessage());
        }
        //System.out.println("Shutdown Threadpool...");
        //pool.shutdown();
        am.stopAllTimers();
        am.stopClientThreads();
        System.out.println("ConnectionManager shutdown complete.");
    }

    @Override
    public void run() {
        while(running){
            try {
                pool.execute(new ClientHandler(ss.accept(), am));
                System.out.println("new Client accepted");
            } catch (SocketException se){
                //Socket Terminated, shutdown thread
                running = false;
            } catch (IOException e) {
                running = false;
                System.out.println("Error on Thread Creation: "+e.getMessage());
            }
        }
        pool.shutdown();
    }

}
